package top.kpromise.note.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Slf4j
public class TimeFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("timeFilter init !");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (!httpServletRequest.getRequestURI().startsWith("/api")) {
            chain.doFilter(request, response);
            return;
        }
        long start = System.currentTimeMillis();
        chain.doFilter(request, response);
        log.info("timeFilter: {} 耗时 {} 毫秒", httpServletRequest.getRequestURI(), System.currentTimeMillis() - start);
    }

    @Override
    public void destroy() {
        log.info("timeFilter destroy!");
    }
}
